package cn.net.zj.scan.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanDevice;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.net.zj.scan.R;
import cn.net.zj.scan.adapter.OutHomeListAdapter;
import cn.net.zj.scan.api.HttpMethods;
import cn.net.zj.scan.bean.LabelBean;
import cn.net.zj.scan.bean.NameBean;
import cn.net.zj.scan.bean.StateBean;
import cn.net.zj.scan.bean.OutHouseBean;
import cn.net.zj.scan.utils.PopupDialog;
import cn.net.zj.scan.utils.ToastUtils;
import cn.net.zj.scan.utils.ZjConfig;
import cn.net.zj.scan.zxing.utils.BeepManager;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;

/**
 * Created by Huan on 2018/5/11.
 * 入库
 */

public class outHouseActivity extends BaseActivity {

    @BindView(R.id.tv_user_name)
    TextView tv_user_name;


    @BindView(R.id.tv_title)
    TextView tv_title;

    @BindView(R.id.et_userCode)
    EditText et_userCode;

    @BindView(R.id.recyclerView)
    RecyclerView recycleView;



    private OutHomeListAdapter adapter;
    private String userCode;
    private String TAG = "出库信息:";
    private boolean isSuccessUserCode = false;
    private BeepManager beepManager;
    ScanDevice sm;
    private final static String SCAN_ACTION = "com.action.SCAN_RESULT";
    private String barcodeStr;
    List<NameBean> nameList = new ArrayList<>();

    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            byte[] barcodeArray = intent.getByteArrayExtra("scanContext");
            barcodeStr = new String(barcodeArray, 0, barcodeArray.length);

            if (userCode!=null && !userCode.equals("") && isSuccessUserCode){
                dealResult(barcodeStr);
            }else {
                ToastUtils.showToast("用户编码为空,请先查询用户码");
            }


            sm.stopScan();
        }

    };

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        if(sm != null) {
            sm.stopScan();
        }
        unregisterReceiver(mScanReceiver);
    }
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction(SCAN_ACTION);
        registerReceiver(mScanReceiver, filter);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_out_house;
    }


    @Override
    public void init() {
        super.init();
        tv_title.setText("出库扫码");

        sm = new ScanDevice();
        sm.setOutScanMode(ScanDevice.SCANNER_MODE_BROADCAST); //接收广播
        sm.openScan();


        adapter = new OutHomeListAdapter(this,orderList);
//        recycleView.setLayoutManager(new StaggeredGridLayoutManager(1,
//                StaggeredGridLayoutManager.VERTICAL));
        LinearLayoutManager layout = new LinearLayoutManager(this);
        layout.setStackFromEnd(true);//列表再底部开始展示,反转后由上面开始展示
        layout.setReverseLayout(true);//列表翻转
        recycleView.setLayoutManager(layout);
        recycleView.setAdapter(adapter);

        adapter.setOnItemClickListener(new OutHomeListAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {

            }

            @Override
            public void onLongClick(final int position) {



                PopupDialog.create(outHouseActivity.this, "提示", "是否删除该标签", "删除", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        deleteLabel(position);

                    }
                }, "取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                },false,false,false).show();


            }
        });

    }

    private void deleteLabel(int position) {

        for (int i=0;i<nameList.size();i++){
            if (orderList.get(position).getC_name().equals(nameList.get(i).getName())){
                if (nameList.get(i).getNumber()>0){
                    nameList.get(i).setNumber(nameList.get(i).getNumber()-1);
                }else {
                    nameList.remove(i);
                }
            }else {

            }
        }
        orderList.remove(position);

        StringBuffer buffer = new StringBuffer();

        for (int i = 0;i < nameList.size();i++){
            buffer.append("商品："+nameList.get(i).getName()+"共出库："+nameList.get(i).getNumber()+"件"+"\r\n");
        }

        adapter.notifyDataSetChanged();
        Log.e("删除后的数据：",buffer.toString());

    }

    @OnClick(R.id.bt_start_out_scan)
    public void scan(Button view){

        if (userCode!=null && !userCode.equals("") && isSuccessUserCode){
            sm.startScan();
        }else {
            ToastUtils.showToast("用户编码为空,请先查询用户码");
        }


    }

    @OnClick(R.id.bt_start_commit)
    public void commit(Button view){

        if (nameList.size()==0){
            ToastUtils.showToast("出库数据为空!请扫码添加!");
            return;
        }

        StringBuffer buffer = new StringBuffer();

        for (int i = 0;i < nameList.size();i++){
            if (nameList.get(i).getNumber()!=0){
                buffer.append("商品："+nameList.get(i).getName()+"  共出库："+nameList.get(i).getNumber()+"套"+"\r\n");
            }

        }

        Log.e("nameList",buffer.toString());


        PopupDialog.create(this, "出库确认", buffer.toString(), "确定出库", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Gson gson = new Gson();
                String dataString = gson.toJson(orderList);
                outLabelData(dataString);
            }
        }, "取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        },false,false,true).show();
    }



    @OnClick(R.id.bt_search)
    public void search(Button view){
            userCode = et_userCode.getText().toString();
            if (!isSuccessUserCode) {
                searchForName(userCode);
            }else {
                ToastUtils.showToast("用户编号已确认,不可修改");
            }
    }

    private List<LabelBean> labelList = new ArrayList<>();
    private void searchForName(String userCode) {

        Observable<StateBean> observable = HttpMethods.getInstance().getFyApi().getCustomerInfo(userCode);

        observable.subscribeOn(Schedulers.io())//切换到io线程请求网络
                .observeOn(AndroidSchedulers.mainThread())//回到主线程处理请求结果
                .subscribe(new Observer<StateBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.d(TAG,"开始获取客户信息");
                        showProgress("请稍后");
                    }

                    @Override
                    public void onNext(final StateBean resBean) {
                        if (resBean.isFlag()){
                            tv_user_name.setText(resBean.getMessage()+"");
                            isSuccessUserCode = true;
                            et_userCode.setInputType(InputType.TYPE_NULL);//来禁止手机软键盘。
//                            et_userCode.setKeyListener(null);

                            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);


                        }else {
                            ToastUtils.showToast(resBean.getMessage()+"");
                        }
                        Log.e(TAG,"返回数据"+new Gson().toJson(resBean)+"");

                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissProgress();
                        Log.e(TAG, "请求失败"+e.getMessage());
                        ToastUtils.showToast("连接失败！"+e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        dismissProgress();
                        Log.d(TAG, "请求成功");
                    }
                });

    }


    private void outLabelData(String dataString) {
        RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),dataString);
        Observable<StateBean> observable = HttpMethods.getInstance().getFyApi().outLabelData(body);
        observable.subscribeOn(Schedulers.io())//切换到io线程请求网络
                .observeOn(AndroidSchedulers.mainThread())//回到主线程处理请求结果
                .subscribe(new Observer<StateBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showProgress("出库中,请稍后...");
                    }
                    @Override
                    public void onNext(final StateBean resBean) {
                        if (resBean.isFlag()){
                            orderList.clear();
                            nameList.clear();
                            adapter.notifyDataSetChanged();
                            beepManager = new BeepManager(outHouseActivity.this,R.raw.sure);
                            beepManager.playBeepSoundAndVibrate();
                            isSuccessUserCode = false;
                            tv_user_name.setText("");
                            et_userCode.setText("");
                            et_userCode.setInputType(InputType.TYPE_CLASS_TEXT);//来开启软键盘。
//                            init();
                            ToastUtils.showToast(""+resBean.getMessage());
                        }else {
                            beepManager = new BeepManager(outHouseActivity.this,R.raw.error);
                            beepManager.playBeepSoundAndVibrate();
                            ToastUtils.showToast(""+resBean.getMessage());
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtils.showToast("连接异常："+e);
                        dismissProgress();
                    }

                    @Override
                    public void onComplete() {
                        dismissProgress();
                    }
                });

    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 根据上面发送过去的请求吗来区别
        switch (requestCode) {
            case ZjConfig.request_out_Code:
                if (data!=null){
                    String result_string = data.getStringExtra("result_string");
                    dealResult(result_string);
                }
                break;
            case ZjConfig.request_in_Code:
                break;
            default:
                break;
        }
    }

    private List<OutHouseBean>  orderList = new ArrayList<>();
    private void dealResult(String label) {
//        String [] b = label.split(" ");  //以每个A作为分割点,得到的是
        String [] b = label.split("\\s+");  //以每个A作为分割点,得到的是
        if (b.length<3){
            ToastUtils.showToast("标签不合法!!!");
            return;
        }
        String [] c = b[3].split("-");
//        tv_user_name.setText("产品名称:"+b[0]+"\r\n"+" 产品配方:"+b[1]+"\r\n"+"  仓位:"+b[2]+"\r\n"+"  批号"+c[0]+"\r\n"+"  本批次顺序号:"+c[1]
//                +"\r\n"+"返回结果"+label);
        OutHouseBean bean = new OutHouseBean();
        bean.setC_name(b[0]+"");
        bean.setC_spectype(b[1]+"");
        bean.setC_stockno(b[2]+"");
        bean.setC_number(b[3]);
        bean.setC_batchno(c[0]);
        bean.setC_cuscode(userCode+"");

        for (int i = 0;i < orderList.size();i++){
            if (orderList.get(i).getC_number().equals(b[3])){
                beepManager = new BeepManager(outHouseActivity.this,R.raw.error);
                beepManager.playBeepSoundAndVibrate();
                ToastUtils.showToast("标签重复!");
                return;
            }

        }
        orderList.add(bean);
        addName(b[0]);
        init();
    }




    private void addName(String name) {
        boolean isContain = false;
        for (int i = 0;i < nameList.size();i++){
            if (nameList.get(i).getName().equals(name)){
                isContain = true;
            }
        }

        if (isContain){
        }else {
            NameBean nameBean = new NameBean();
            nameBean.setName(name);
            nameBean.setNumber(0);
            nameList.add(nameBean);
        }
        for (int i = 0;i < nameList.size();i++){
            if (nameList.get(i).getName().equals(name)){
                nameList.get(i).setNumber(nameList.get(i).getNumber()+1);
            }
        }



    }
}
